﻿using Azure.Core;
using CommonBaseEntityDb.Db;
using Enums;
using Model.Dto;
using Model.Entity;
using Model.Request;
using SqlSugar;
using TemplateInterfaceDao;

namespace TemplateDao
{
    /// <summary>
    /// Users
    /// </summary>
    public class UsersDao : TemplateExSugarRespository<Users>, IUsersDao
    {
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async Task<Users> GetUser(string username, string password)
        {
            return await Context.Queryable<Users>()
                .Where(x => x.Username == username && x.PasswordHash == password && x.Status == ((int)UserStatusEnum.启用))
                .FirstAsync();
        }

        /// <summary>
        /// 根据查询条件获取用户列表
        /// </summary>
        /// <param name="req">查询条件</param>
        /// <param name="isPage">是否分页(默认分页)</param>
        /// <returns></returns>
        public async Task<(List<UserDto>, RefAsync<int>)> GetSearchUsers(GetSearchUsersRequest req, bool isPage = true)
        {
            //所有数据条数
            RefAsync<int> totalNumber = 0;

            //查询条件
            var expressionable = Expressionable.Create<Users>();
            expressionable.AndIF(!string.IsNullOrWhiteSpace(req.userName), (a) => a.Username.Contains(req.userName));//用户名
            expressionable.AndIF(!string.IsNullOrWhiteSpace(req.realName), (a) => a.RealName.Contains(req.realName));//真实名
            var result = Context.Queryable<Users>().Where(expressionable.ToExpression());
            
            if (isPage)
            {
                return (await result.OrderByDescending((a) => a.CreateTime).Select((a) => new UserDto(){ }, true)
                    .ToPageListAsync(req.PageNum, req.PageSize, totalNumber), totalNumber);
            }
            else
            {
                return (await result.OrderByDescending((a) => a.CreateTime).Select((a) => new UserDto(){ }, true)
                    .ToListAsync(),0);
            }
        }
    }
}
